setCenter = function(ele) {
    if (!ele instanceof jQuery) return false;
    var w = jQuery(window);
    var config = {
        left: ((w.width() - ele.outerWidth()) / 2) + w.scrollLeft(),
        top: ((w.height() - ele.outerHeight()) / 2) + w.scrollTop()
    };
    ele.css({left:config.left, top:config.top});
    delete w,config;
}

function moveStart(e, ele) {
    ele.onmousemove = mousemove;
    ele.onmouseup = mouseup;
    ele.setCapture ? ele.setCapture() : function(){};
    e = window.event?window.event:e;
    var dragData = {x:e.clientX, y:e.clientY};
    var backData = {x:parseInt(ele.style.top), y:parseInt(ele.style.left)};

    function mousemove(){
        var event = window.event?window.event:e;
        var left = event.clientX - dragData.x + parseInt(ele.style.left);
        var top = event.clientY - dragData.y + parseInt(ele.style.top);
        ele.style.left = left;
        ele.style.top = top;
        dragData = {x:event.clientX, y:event.clientY};
    }

    function mouseup(){
        var event = window.event?window.event:e;
        ele.onmousemove = null;
        ele.onmouseup = null;
        if(event.clientX < 1 || event.clientY < 1 || event.clientX > document.body.clientWidth || event.clientY > document.body.clientHeight) {
            ele.style.left = backData.y;
            ele.style.top = backData.x;
        }
        ele.releaseCapture ? ele.releaseCapture():function(){};
    }


}

var loading = function() {
    var html = '<div id="loading" class="loading"><s></s><div class="loading_c">正在处理请求，请等候...</div></div>';
    $('body').append(html);
    loading.loadbar = $('#loading');
}
loading.has = false;
loading.show = function() {
    if(!loading.loadbar) loading();
    setCenter(loading.loadbar);
    loading.loadbar.css({visibility:'visible', opacity:0});
    loading.loadbar.animate({opacity:1},100);
    loading.has=true;
}
loading.hide = function(){
    if(!loading.loadbar) return false;
    loading.loadbar.animate({opacity:0}, 100, null, function(){
        loading.loadbar.css({visibility:'hidden'});
    });
    loading.has = false;
}

var panelList = [];
panel = function() {
    panelList.push(this);
    var id = panel.getId();
    this.id = (id.key+'').replace('.','');
    this.guidIndex = id.index;
    this.body = jQuery('body:eq(0)');
    this.container = '<div id="panel_w_'+this.id+'" class="panel_w"><div class="panel_c"><div class="panel_t"><a class="panel_s" href="javascript:void(0)"></a><h2>标题</h2></div><div class="panel_cont"></div><div class="panel_b"></div></div></div>';
    if(!panel.mask) {
        panel.mask = '<div id="panel_m" class="panel_m">'+(($.browser.version == '6.0') ? '<iframe></iframe>' : '') + '</div>';
        this.trace = panel.mask + this.container;
    } else {
        this.trace = this.container;
    }

    this.body.prepend(this.trace);
    this.title = null;
    this.content = null;
    this.buttons = null;
    this.close = null;
    this.width = 200;

    this.init();
}
panel.guid =[];
panel.zindex = 1;
panel.maskDisplay = function(method){
    if (method == 'hide') {
        for (var i = 0; i < panel.guid.length; i++) {
            if (panel.guid[i].display == 'show')
                return;
        }

        panel.mask.animate({opacity:0}, 150, null, function() {
            panel.mask.css({visibility:'hidden'});
        });
    } else if(method == 'show') {
        if (panel.mask.css('visibility') == 'visible') {
            return;
        }
        panel.mask.css({visibility:'visible', opacity:0});
        panel.mask.animate({'opacity':0.5}, 150);
    }
}

panel.getId = function() {
    var r = Math.random();
    var len = panel.guid.length;
    // 确定唯一性
    while(panel.keyExists(r)) {
        r = Math.random();
    }
    panel.guid[len] = {
        key:r,
        display:'hide'
    };
    return {
        key:r,
        index:len
    };
}

panel.keyExists = function(k) {
    for(var i = 0; i < panel.guid.length; i++) {
        if(panel.guid[i].key = k) {
            return true;
        }
    }
    return false;
}

panel.prototype = {
    init : function() {
        var content, title;
        panel.mask = this.body.find('#panel_m');

        this.trace = this.body.find('#panel_w_' + this.id);
        content = this.trace.children('.panel_c');
        title = content.children('.panel_t');
        this.title = title.children('h2');
        this.close = title.children('a.panel_s');
        this.content = content.children('div.panel_cont');
        this.buttons = content.children('div.panel_b');
        var _self = this;
        // 绑定移动
        this.title.mousedown(function(e){
             moveStart(e, title[0]);
        });

        this.close.click(function(){
            _self.setDisplay('hide'); //TODO
            return false;
        });

        if(panel.guid.length == 1) {
            this.initMaskStyle();// TODO
        }
        //TODO 这里是否需要优化,考虑使用fixed
        $(window).bind('scroll',function(){
           _self.setCenter();
        }).resize(function(){
            _self.initMaskStyle();
            _self.setCenter();
        });
    },
    initMaskStyle: function(){
        var win = jQuery(window);
        var width = (this.body.width() < win.width() ? win.width() : this.body.width());
        panel.mask.css('display', 'none');
        var height = win.height();
        panel.mask.css('display', 'block');
        panel.mask.width(width);
        panel.mask.height(height);
        panel.mask.css('opacity', 0.5);
    },
    setCenter:function() {
        var w = jQuery(window);
        var width = ((this.body.width() - this.trace.outerWidth())/2) + w.scrollLeft();
        var height = ((w.height() - this.trace.outerHeight())/2)+w.scrollTop();
        var top = w.scrollTop();
        this.trace.css({
            left:width,
            top:height
        });
        panel.mask.css('top', top);//TODO 考虑使用fixed
    },
    setDisplay: function(method){
        var _self = this;
        if(method == 'hide' || method =='show') {
            panel.mask.stop(false, true);
            this.trace.stop(false, true);
            panel.guid[this.guidIndex].display = method;
            panel.maskDisplay(method);
            if(method == 'hide') {
                this.trace.animate({
                    opacity:0
                }, 150, null, function(){
                    $(this).css('visibility', 'hidden');
                    try {
                        _self.onHide();
                    } catch(e) {}
                });
                //TODO 从dom中删除元素
                this.trace.remove();
            } else if(method == 'show') {
                this.setCenter();
                this.trace.css({
                    visibility:'visible',
                    opacity:0
                });
                this.trace.animate({
                    opacity:1
                }, 150, function(){
                    try{
                        _self.onShow();
                    }catch(e){}
                })
            }
        }
    },
    setContent:function(title, content, buttons){
        var btnStr = '';
        if(title) this.title.html(title);
        if(content) this.content.html(content);
        if(buttons) {
            for(var i = 0; i < buttons.length; i++) {
                btnStr +=buttons[i].html+(((i+1) == buttons.length) ? '' : ' ');
                this.buttons.html(btnStr);
                this.bindEvent(buttons);//TODO
            }
        }
        this.setCenter();
    },
    setTitle:function(title) {
        if(title)
            this.title.html(title);
    },
    appendContent: function(content) {
        this.content.html('');
        this.content.append(content);
        this.setCenter();
    },
    bindEvent:function(buttons) {
        var a = this.buttons.find('a'), idx, _self = this;
        a.click(function(){
            idx = a.index(this);
            if(buttons[idx].callback == 'close') {
                _self.setDisplay('hide');
            } else {
                buttons[idx].callback();
                return false;
            }
        })
    },
    setWidth: function(width) {
        this.trace.find('div.panel_c').width(width);
        this.setCenter();
    },
    getButton: function(text, color, callback){
        if(!text || !color) return null;
        var html;
        if(color == 'blue' || color == 'yellow' || color == 'gray') {
            color = /^.?/.exec(color);
            html = '<a href="javascript:void(0)" class="but b_2_' + color +'"><u></u>'+text+'</a>';
        } else if(color == 'href') {
            html = '<a href="javascript:void(0)" class="txthref">' + text + '</a>';
        }
        return {
            html:html,
            callback:callback
        }
    },
    setDefaultCloseDisplay:function(method) {
        var close = this.getThis().find('a.panel_s');//TODO
        if(method = 'hide') {
            close.hide();
        }
        else{
            close.show();
        }
        delete close;
    },
    setDefaultButtonDisplay:function(m) {
        if(m == 'hide') {
            this.buttons.hide();
        } else {
            this.buttons.show();
        }
        this.setCenter();
    },
    getThis:function() {
        return this.trace;
    }
}

var ipanel = panel.prototype;
InfoPanel = function() {
    var ip = new panel();
    ipanel = ip;
    ip.setWidth(350);
    ip.setContent('系统提示', null, [ipanel.getButton('确定','gray','close')]);
    ip.getThis().addClass('panel_i');

    ip.onShow = function(){
        try {
            InfoPanel.onShow();
        } catch(e) {}
    }
    ip.onHide = function() {
        try{
            InfoPanel.onHide();
        }catch(e){}
    }
}
InfoPanel._timer = null;
InfoPanel.hasInit = false;
/**
 *
 * @param menu
 * @param info i,o,e
 * @param time
 * @param btn
 * @param m
 */
InfoPanel.show = function(menu, info, time, btn, m) {
    if(InfoPanel.hasInit == false) {
        InfoPanel();
        InfoPanel.hasInit = true;
    }
    var info = info || "i";
    ipanel.setContent(null, '<div class="p_info clearfix"><u class="msg m_1_'+info+'"></u><p class="p_info_c '+(m?'':'m10') +' ml15">'+ menu +'</p></div>', ((btn)?btn:[ipanel.getButton('确定','gray', 'close')]));
    ipanel.setDisplay('show');
    if(time && /^[0-9]*$/.test(time)) {
        InfoPanel._timer = window.setTimeout(function(){
            window.clearTimeout(InfoPanel._timer);
            InfoPanel.hide();
        }, time)
    }
}

InfoPanel.hide = function(){
    ipanel.setDisplay('hide');
    window.clearTimeout(InfoPanel._timer);
}